package com.tolerate.managespringboot.Utils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.tolerate.managespringboot.entity.User;
import com.tolerate.managespringboot.exception.BusinessException;
import com.tolerate.managespringboot.service.UserService;
import com.tolerate.managespringboot.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class TokenUtils {

    private static UserService userServiceStatic;


    @Autowired
    private UserService userService;

    //  使用了@PostConstruct注解，表示在Bean初始化之后调用该方法
    @PostConstruct
    public void setUserServiceImpl() {
        userServiceStatic = userService;
    }

    /**
     * 生成token
     *
     * @param userId   用户id
     * @param userName 密钥
     * @return
     */
    public static String getToken(String userId, String userName) {
        return JWT.create().withAudience(userId)  // 将userId保存到token里面，作为载荷
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) // 2小时后token过期
                .sign(Algorithm.HMAC256(userName));  // userName作为token的密钥
    }

    /**
     * 通过token，获取当前登录用户的信息
     * 这样写不限制传递的参数，可以在任意地方使用，不用每次都传参
     *
     * @return
     */
    public static User getCurrentUserMessage() {
        //    通过这行代码，可以获取到当前正在进行的HTTP请求对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (StrUtil.isNotBlank(token)) {
            try {
                String userId = JWT.decode(token).getAudience().get(0);
                return userServiceStatic.getById(userId);
            } catch (Exception e) {
                throw new BusinessException(401, "token验证失败，请重新登录");
            }
        } else {
            return null;
        }
    }
}
